﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace LsTool
{
    public class XmlCom
    {
        public static SortedDictionary<string, string> XmlToDictionary(string xml)
        {
            var sortedDictionary = new SortedDictionary<string, string>();
            if (string.IsNullOrEmpty(xml))
            {
                return sortedDictionary;
            }
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xml);
                XmlNode xmlNode = xmlDoc.FirstChild;//获取到根节点<xml>
                XmlNodeList nodes = xmlNode.ChildNodes;
                foreach (XmlNode xn in nodes)
                {
                    XmlElement xe = (XmlElement)xn;
                    sortedDictionary.Add(xe.Name, xe.InnerText); //获取xml的键值对到WxPayData内部的数据中
                }
                return sortedDictionary;
            }
            catch (Exception)
            {

                return sortedDictionary;
            }

        }


        /// <summary>
        /// 转成XML
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string ParseXml(SortedDictionary<string, string> parameters)
        {

            var sb = new StringBuilder();
            sb.Append("<xml>");
            var akeys = new ArrayList(parameters.Keys);
            foreach (string k in akeys)
            {
                var v = (string)parameters[k];
                if (Regex.IsMatch(v, @"^[0-9.]$"))
                {
                    sb.Append("<" + k + ">" + v + "</" + k + ">");
                }
                else
                {
                    sb.Append("<" + k + "><![CDATA[" + v + "]]></" + k + ">");
                }
            }
            sb.Append("</xml>");
            return sb.ToString();
        }
        /// <summary>
        /// 转成XML
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string ParseXml(Dictionary<string, string> parameters)
        {

            var sb = new StringBuilder();
            sb.Append("<xml>");
            var akeys = new ArrayList(parameters.Keys);
            foreach (string k in akeys)
            {
                var v = (string)parameters[k];
                if (Regex.IsMatch(v, @"^[0-9.]$"))
                {
                    sb.Append("<" + k + ">" + v + "</" + k + ">");
                }
                else
                {
                    sb.Append("<" + k + "><![CDATA[" + v + "]]></" + k + ">");
                }
            }
            sb.Append("</xml>");
            return sb.ToString();
        }
    }
}